package com.gary.cloud.redis;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author peng_rui
 * @date 2022/4/19
 */
public class RedisLock implements ILock{

    private RedisTemplate<String, Object> redisTemplate;
    private String name = "order";
    private static final String PREFIX = "lock:" + UUID.randomUUID();

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public RedisLock() {}

    public RedisLock(RedisTemplate<String, Object> redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public Boolean tryLock(Long timeoutSec) {
        long threadId = Thread.currentThread().getId();
        //尝试加锁
        return redisTemplate.opsForValue().setIfAbsent(PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
    }

    @Override
    public void unLock() {
        //1 缺点 单纯的删除：当出现操作阻塞触发锁的超时释放，此时阻塞恢复，有继续删除则会产生误删锁的问题
//        return redisTemplate.delete(PREFIX + name);
        //2 在删除前 进行判断，判断当前的锁的值是否与我当前的锁的值相等，相等才删除，不相等不处理
        // 由于判断和删除是非原子性的2部操作，可能会在判断完成后 发生阻塞，此时有因为超时问题导致锁被释放，继续出现误删问题

        //3 使用lua脚本，将 方式2 的代码进行原子化
        redisTemplate.execute(UNLOCK_SCRIPT, Arrays.asList(PREFIX + name), Thread.currentThread().getId());
    }
}
